<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { h, ref } from 'vue'

import { Page, useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Button, Input, Spin, Tag, Tooltip } from 'ant-design-vue'

import CountTabs from '#/adapter/component/count-tabs.vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getAdminList } from '#/api/common'
import { getGoodsPriceLog, getTabsIndex } from '#/api/goodsPriceLog'

import info from './info.vue'

const keyword4 = ref('')
const fetching = ref(false)
async function fetchgetFactoryIndex({ keyword = '' }: Record<string, any>) {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 999,
    initKey: 'id',
    initValue: undefined,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.realname,
    value: item.id,
  }))
}
const formOptions: any = {
  collapsed: true,
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
  wrapperClass: 'grid-cols-5',
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'goods*goods_no',
      label: '货号',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'template*template_no',
      label: '简码',
      operator: 'LIKE',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '模糊搜索',
      },
      fieldName: 'create_text',
      label: '申请原因',
      operator: 'LIKE',
    },

    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchgetFactoryIndex,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword4.value = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword4.value || undefined,
          },
          showSearch: true,
          allowClear: true,
        }
      },
      fieldName: 'createAdmin*id',
      operator: '=',
      label: '发起人',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'RangePicker',
      componentProps: {
        allowClear: true,
        placeholder: ['开始时间', '结束时间'],
        style: { width: '100%' },
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'create_time',
      label: '发起时间',
      operator: 'RANGE',
      render: 'datetime',
    },
  ],
  // 是否可展开
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
}
/**
 *  快速查询查询
 */
const quick_search = ref()
function doSearch() {
  gridApi.query()
}
const gridOptions: VxeTableGridOptions = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  height: 'auto',
  columns: [
    { field: 'id', title: 'ID' },
    { field: 'type', title: '审批类型' },
    { field: 'goods.goods_no', title: '货号' },
    { field: 'template.template_no', title: '简码' },
    { field: 'info', title: '申请修改内容', slots: { default: 'info' } },
    { field: 'create_text', title: '申请原因', width: 500 },
    { field: 'status', title: '审批状态', slots: { default: 'status' } },
    { field: 'text_arr', title: '审批记录', width: 500, slots: { default: 'text_arr' } },
    { field: 'createAdmin.realname', title: '发起人', width: 180 },
    { field: 'create_time', title: '发起时间', width: 160 },
    { field: 'action', title: '操作', fixed: 'right', slots: { default: 'action' } },
  ],
  cellConfig: {
    height: 80,
  },
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        // 1. 过滤空值
        const search = await gridApi.formApi.getFiltersValues()
        // 2. 调接口
        const res = await getGoodsPriceLog({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          status: activeKey.value,
          quick_search: quick_search.value,
        })
        const res1 = await getTabsIndex({ search, quick_search: quick_search.value })
        tabsList.value = res1.map((it: any) => ({
          title: it.label,
          value: it.value,
          count: it.count,
          type: it.value === 99 ? 'default' : it.type,
        }))

        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },
  toolbarConfig: {
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
}

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions })

const activeKey = ref('all')
const tabsList: any = ref([])

function resetQuery() {
  gridApi.query()
}

const [infoModal, infoModalApi] = useVbenModal({
  connectedComponent: info,
})

function open(row: any) {
  infoModalApi.setData({ data: row }).open()
}
</script>

<template>
  <Page auto-content-height>
    <infoModal @push-data="gridApi.reload()" />
    <Grid>
      <template #toolbar-actions>
        <div style="margin-top: 10px; width: 1000px">
          <CountTabs v-model:active-key="activeKey" :list="tabsList" @click-tab="resetQuery()" :disabled="false" />
        </div>
      </template>

      <template #status="{ row }">
        <template v-if="row.status === 0"><Tag color="warning">待一审</Tag></template>
        <template v-if="row.status === 1"><Tag color="warning">待二审</Tag></template>
        <template v-if="row.status === 2"><Tag color="success">已通过</Tag></template>
        <template v-if="row.status === 3"><Tag color="error">已拒绝</Tag></template>
        <template v-if="row.status === 99"><Tag color="default">已作废</Tag></template>
      </template>
      <template #toolbar-tools>
        <Input v-model:value="quick_search" allow-clear placeholder="通过id模糊搜索" style="width: 200px; margin-right: 8px" @change="doSearch" />
      </template>
      <template #info="{ row }">
        <Tooltip>
          <template #title>
            <div v-if="row.updateData">
              <!-- 商品价格变更信息 -->
              <div v-if="row.updateData.goodsPrice && row.updateData.goodsPrice.length > 0" class="mb-2">
                <div class="mb-1 font-bold">货品资料价格:</div>
                <div v-for="(item, index) in row.updateData.goodsPrice" :key="`goods-${index}`" class="mb-1">
                  <span>{{ item.fieldName }}：</span>
                  <span>{{ item.origin }} → {{ item.destination }}</span>
                </div>
              </div>
              <!-- 供应商价格变更信息 -->
              <div v-if="row.updateData.supplyPrice && row.updateData.supplyPrice.length > 0">
                <div class="mb-1 font-bold">货品供应商价格:</div>
                <div v-for="(item, index) in row.updateData.supplyPrice" :key="`supply-${index}`" class="mb-1">
                  <span>{{ item.fieldName }}：</span>
                  <span>{{ item.origin }} → {{ item.destination }}</span>
                </div>
              </div>
            </div>
          </template>
          查看详情
        </Tooltip>
      </template>

      <template #text_arr="{ row }">
        <template v-for="item in row.text_arr" :key="item.username">
          <div>
            <span>处理人:{{ item.username }}</span>
            <span> 处理时间:{{ item.time }} </span>
            <span> 处理结果:{{ item.text }} </span>
          </div>
        </template>
      </template>

      <template #action="{ row }">
        <Button v-if="row.status === 0 || row.status === 1" type="primary" @click="open(row)">审核</Button>
      </template>
    </Grid>
  </Page>
</template>
